<!--
  成绩单详情页面
-->
<template>
  <div class="sheet-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button
          text
          :icon="ArrowLeft"
          @click="goBack"
          class="back-btn"
        >
          返回成绩单列表
        </el-button>
        <h1>{{ gradeSheet?.name }}</h1>
        <div class="sheet-meta">
          <el-tag :type="getStatusType(gradeSheet?.status)">
            {{ getStatusText(gradeSheet?.status) }}
          </el-tag>
          <span class="exam-info">{{ gradeSheet?.examination_title }}</span>
          <span class="creator">创建者：{{ gradeSheet?.creator_name }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-button
          v-if="canEditSheet"
          :icon="Edit"
          @click="editSheet"
        >
          编辑
        </el-button>
        <el-button
          v-if="canCalculateSheet"
          :icon="Refresh"
          @click="calculateGrades"
        >
          重新计算
        </el-button>
        <el-button
          v-if="canReviewSheet"
          type="warning"
          @click="showReviewDialog = true"
        >
          审核
        </el-button>
        <el-button
          v-if="canPublishSheet"
          type="success"
          @click="publishSheet"
        >
          发布
        </el-button>
        <el-dropdown @command="handleSheetAction" trigger="click">
          <el-button>
            更多<el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="export">
                <el-icon><Download /></el-icon>
                导出成绩
              </el-dropdown-item>
              <el-dropdown-item command="report">
                <el-icon><Document /></el-icon>
                生成报告
              </el-dropdown-item>
              <el-dropdown-item command="notify">
                <el-icon><Bell /></el-icon>
                发送通知
              </el-dropdown-item>
              <el-dropdown-item
                command="delete"
                divided
                v-if="canDeleteSheet"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 标签页 -->
    <el-card>
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <div class="basic-info">
            <!-- 成绩统计 -->
            <el-row :gutter="20" class="stats-row">
              <el-col :span="6">
                <el-statistic title="参考人数" :value="gradeSheet?.total_students || 0" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="提交人数" :value="gradeSheet?.submitted_count || 0" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="平均分" :value="gradeSheet?.average_score || 0" :precision="2" />
              </el-col>
              <el-col :span="6">
                <el-statistic title="及格率" :value="gradeSheet?.pass_rate || 0" suffix="%" />
              </el-col>
            </el-row>

            <!-- 详细信息 -->
            <el-descriptions :column="2" border class="detail-info">
              <el-descriptions-item label="考试名称">{{ gradeSheet?.examination_title }}</el-descriptions-item>
              <el-descriptions-item label="考试时间">{{ formatDateTime(gradeSheet?.exam_date) }}</el-descriptions-item>
              <el-descriptions-item label="满分">{{ gradeSheet?.total_score }} 分</el-descriptions-item>
              <el-descriptions-item label="及格分">{{ gradeSheet?.passing_score }} 分</el-descriptions-item>
              <el-descriptions-item label="最高分">{{ gradeSheet?.max_score || '--' }} 分</el-descriptions-item>
              <el-descriptions-item label="最低分">{{ gradeSheet?.min_score || '--' }} 分</el-descriptions-item>
              <el-descriptions-item label="标准差">{{ gradeSheet?.std_deviation || '--' }}</el-descriptions-item>
              <el-descriptions-item label="创建时间" :span="2">{{ formatDateTime(gradeSheet?.created_at) }}</el-descriptions-item>
            </el-descriptions>

            <!-- 成绩分布图表 -->
            <div class="chart-section">
              <h3>成绩分布</h3>
              <div id="scoreChart" style="height: 300px"></div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 成绩列表 -->
        <el-tab-pane label="成绩列表" name="grades">
          <div class="grades-section">
            <!-- 筛选和操作 -->
            <div class="section-header">
              <div class="header-left">
                <el-input
                  v-model="gradeFilter.keyword"
                  placeholder="搜索学生姓名或学号"
                  clearable
                  style="width: 200px"
                  @keyup.enter="loadGrades"
                />
                <el-select
                  v-model="gradeFilter.status"
                  placeholder="筛选状态"
                  clearable
                  style="width: 120px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="及格" value="passed" />
                  <el-option label="不及格" value="failed" />
                  <el-option label="缺考" value="absent" />
                </el-select>
                <el-button type="primary" @click="loadGrades">搜索</el-button>
                <el-button @click="resetGradeFilter">重置</el-button>
              </div>
              <div class="header-right">
                <el-button
                  :icon="Download"
                  @click="exportGrades"
                  :disabled="grades.length === 0"
                >
                  导出
                </el-button>
                <el-button
                  :icon="Upload"
                  @click="showImportDialog = true"
                  v-if="canImportGrades"
                >
                  导入
                </el-button>
              </div>
            </div>

            <!-- 成绩表格 -->
            <el-table
              :data="grades"
              v-loading="gradesLoading"
              @sort-change="handleGradeSortChange"
            >
              <el-table-column type="index" label="排名" width="60" />
              <el-table-column label="姓名" prop="student_name" sortable="custom" />
              <el-table-column label="学号" prop="student_id" sortable="custom" />
              <el-table-column label="班级" prop="class_name" />
              <el-table-column label="得分" width="100" sortable="custom">
                <template #default="{ row }">
                  <span :class="getScoreClass(row.score, gradeSheet?.passing_score)">
                    {{ row.score || '--' }} 分
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="等级" width="80">
                <template #default="{ row }">
                  <el-tag :type="getGradeType(row.grade)">
                    {{ row.grade || '--' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStudentStatusType(row.status)">
                    {{ getStudentStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="用时" width="100">
                <template #default="{ row }">
                  {{ formatDuration(row.time_spent) }}
                </template>
              </el-table-column>
              <el-table-column label="提交时间" width="150">
                <template #default="{ row }">
                  {{ formatDateTime(row.submitted_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                  <div class="action-buttons">
                    <el-button
                      text
                      type="primary"
                      size="small"
                      @click="viewStudentPaper(row)"
                    >
                      查看试卷
                    </el-button>
                    <el-button
                      text
                      size="small"
                      @click="viewStudentDetail(row)"
                    >
                      详情
                    </el-button>
                    <el-button
                      v-if="row.status === 'submitted' && canAdjustGrade(row)"
                      text
                      type="warning"
                      size="small"
                      @click="adjustGrade(row)"
                    >
                      调整
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-wrapper" v-if="gradesTotal > 0">
              <el-pagination
                v-model:current-page="gradesPage"
                v-model:page-size="gradesPageSize"
                :total="gradesTotal"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="loadGrades"
                @current-change="loadGrades"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 成绩分析 -->
        <el-tab-pane label="成绩分析" name="analysis">
          <div class="analysis-section">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card class="analysis-card">
                  <h3>分数段分布</h3>
                  <div id="segmentChart" style="height: 250px"></div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="analysis-card">
                  <h3>班级对比</h3>
                  <div id="classChart" style="height: 250px"></div>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-card class="analysis-card">
                  <h3>题目得分率分析</h3>
                  <div id="questionChart" style="height: 300px"></div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 成绩申诉 -->
        <el-tab-pane label="成绩申诉" name="appeals">
          <div class="appeals-section">
            <div class="section-header">
              <div class="header-left">
                <h3>申诉列表</h3>
                <el-tag :type="appealsCount > 0 ? 'danger' : 'info'">
                  {{ appealsCount }} 条申诉
                </el-tag>
              </div>
              <div class="header-right">
                <el-button
                  type="primary"
                  @click="handleAppeals"
                  :disabled="appealsCount === 0"
                >
                  批量处理
                </el-button>
              </div>
            </div>

            <el-table :data="appeals" v-loading="appealsLoading">
              <el-table-column label="学生" prop="student_name" />
              <el-table-column label="学号" prop="student_id" />
              <el-table-column label="原始成绩" width="100">
                <template #default="{ row }">
                  {{ row.original_score }} 分
                </template>
              </el-table-column>
              <el-table-column label="期望成绩" width="100">
                <template #default="{ row }">
                  {{ row.expected_score }} 分
                </template>
              </el-table-column>
              <el-table-column label="申诉理由" min-width="200">
                <template #default="{ row }">
                  <div class="appeal-reason">
                    {{ row.reason }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getAppealStatusType(row.status)">
                    {{ getAppealStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="申请时间" width="150">
                <template #default="{ row }">
                  {{ formatDateTime(row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <div class="action-buttons">
                    <el-button
                      text
                      size="small"
                      @click="viewAppealDetail(row)"
                    >
                      查看
                    </el-button>
                    <el-button
                      v-if="row.status === 'pending'"
                      text
                      type="success"
                      size="small"
                      @click="approveAppeal(row)"
                    >
                      通过
                    </el-button>
                    <el-button
                      v-if="row.status === 'pending'"
                      text
                      type="danger"
                      size="small"
                      @click="rejectAppeal(row)"
                    >
                      拒绝
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="showReviewDialog"
      title="成绩单审核"
      width="500px"
    >
      <el-form :model="reviewForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="reviewForm.status">
            <el-radio value="approved">通过</el-radio>
            <el-radio value="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
            v-model="reviewForm.review_notes"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmReview"
        >
          确认审核
        </el-button>
      </template>
    </el-dialog>

    <!-- 成绩调整对话框 -->
    <el-dialog
      v-model="showAdjustDialog"
      title="成绩调整"
      width="400px"
    >
      <el-form :model="adjustForm" label-width="100px">
        <el-form-item label="学生姓名">
          <span>{{ adjustForm.student_name }}</span>
        </el-form-item>
        <el-form-item label="原始成绩">
          <span>{{ adjustForm.original_score }} 分</span>
        </el-form-item>
        <el-form-item label="新成绩">
          <el-input-number
            v-model="adjustForm.new_score"
            :min="0"
            :max="gradeSheet?.total_score"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="调整原因">
          <el-select v-model="adjustForm.adjustment_type" style="width: 100%">
            <el-option label="手动调整" value="manual" />
            <el-option label="曲线调整" value="curve" />
            <el-option label="加分" value="bonus" />
          </el-select>
        </el-form-item>
        <el-form-item label="说明">
          <el-input
            v-model="adjustForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调整原因"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAdjustDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmAdjust"
        >
          确认调整
        </el-button>
      </template>
    </el-dialog>

    <!-- 成绩导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="导入成绩"
      width="500px"
    >
      <div class="import-content">
        <el-upload
          class="upload-area"
          drag
          accept=".xlsx,.xls,.csv"
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 Excel、CSV 格式，文件大小不超过 10MB
            </div>
          </template>
        </el-upload>

        <div class="import-tips">
          <h4>导入说明：</h4>
          <ul>
            <li>Excel文件需包含：学号、姓名、成绩等字段</li>
            <li>导入的成绩将覆盖现有数据</li>
            <li>请确保文件格式正确</li>
          </ul>
        </div>
      </div>
      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="!importFile"
          :loading="importLoading"
          @click="confirmImport"
        >
          开始导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores'
import { gradingApi } from '@/api'
import * as echarts from 'echarts'
import type { GradeSheet } from '@/types'
import {
  ArrowLeft,
  Edit,
  Refresh,
  Download,
  Upload,
  Document,
  Bell,
  Delete,
  ArrowDown,
  UploadFilled
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

const sheetId = Number(route.params.id)
const activeTab = ref('basic')

// 响应式数据
const loading = ref(false)
const gradeSheet = ref<GradeSheet | null>(null)
const grades = ref<any[]>([])
const appeals = ref<any[]>([])
const gradesLoading = ref(false)
const appealsLoading = ref(false)
const gradesTotal = ref(0)
const appealsCount = computed(() => appeals.value.length)

// 筛选
const gradeFilter = reactive({
  keyword: '',
  status: ''
})

// 分页
const gradesPage = ref(1)
const gradesPageSize = ref(20)
const gradeSortField = ref('')
const gradeSortOrder = ref('')

// 对话框
const showReviewDialog = ref(false)
const showAdjustDialog = ref(false)
const showImportDialog = ref(false)
const importFile = ref<File | null>(null)
const importLoading = ref(false)

// 表单数据
const reviewForm = reactive({
  status: 'approved',
  review_notes: ''
})

const adjustForm = reactive({
  grade_id: 0,
  student_name: '',
  original_score: 0,
  new_score: 0,
  adjustment_type: 'manual',
  reason: ''
})

// 图表实例
let scoreChart: echarts.ECharts | null = null
let segmentChart: echarts.ECharts | null = null
let classChart: echarts.ECharts | null = null
let questionChart: echarts.ECharts | null = null

// 计算属性
const canEditSheet = computed(() => {
  return authStore.hasPermission('grading:write') &&
         gradeSheet.value?.status === 'draft' &&
         (gradeSheet.value?.creator === authStore.user?.id || authStore.hasRole('admin'))
})

const canCalculateSheet = computed(() => {
  return authStore.hasPermission('grading:write') &&
         (gradeSheet.value?.status === 'draft' || gradeSheet.value?.status === 'reviewed')
})

const canReviewSheet = computed(() => {
  return authStore.hasPermission('grading:write') &&
         gradeSheet.value?.status === 'draft' &&
         (gradeSheet.value?.creator === authStore.user?.id || authStore.hasRole('admin'))
})

const canPublishSheet = computed(() => {
  return authStore.hasPermission('grading:write') &&
         gradeSheet.value?.status === 'reviewed' &&
         (gradeSheet.value?.creator === authStore.user?.id || authStore.hasRole('admin'))
})

const canDeleteSheet = computed(() => {
  return authStore.hasPermission('grading:delete') &&
         gradeSheet.value?.status !== 'published' &&
         (gradeSheet.value?.creator === authStore.user?.id || authStore.hasRole('admin'))
})

const canImportGrades = computed(() => {
  return authStore.hasPermission('grading:write') &&
         ['draft', 'reviewed'].includes(gradeSheet.value?.status || '')
})

const canAdjustGrade = (row: any) => {
  return authStore.hasPermission('grading:write') &&
         row.status === 'submitted'
}

// 加载成绩单信息
const loadGradeSheet = async () => {
  try {
    const response = await gradingApi.getGradeSheet(sheetId)
    gradeSheet.value = response.data
  } catch (error) {
    console.error('Failed to load grade sheet:', error)
    ElMessage.error('加载成绩单失败')
  }
}

// 加载成绩列表
const loadGrades = async () => {
  gradesLoading.value = true
  try {
    // TODO: 实现成绩列表API调用
    // const params = {
    //   page: gradesPage.value,
    //   page_size: gradesPageSize.value,
    //   search: gradeFilter.keyword || undefined,
    //   status: gradeFilter.status || undefined,
    //   ordering: gradeSortField.value ?
    //     (gradeSortOrder.value === 'ascending' ? gradeSortField.value : `-${gradeSortField.value}`) :
    //     undefined
    // }
    // const response = await getGrades(sheetId, params)
    // grades.value = response.data.results
    // gradesTotal.value = response.data.count
  } catch (error) {
    console.error('Failed to load grades:', error)
    ElMessage.error('加载成绩失败')
  } finally {
    gradesLoading.value = false
  }
}

// 加载申诉列表
const loadAppeals = async () => {
  appealsLoading.value = true
  try {
    // TODO: 实现申诉列表API调用
  } catch (error) {
    console.error('Failed to load appeals:', error)
  } finally {
    appealsLoading.value = false
  }
}

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 成绩分布图
    const scoreChartEl = document.getElementById('scoreChart')
    if (scoreChartEl) {
      scoreChart = echarts.init(scoreChartEl)
      updateScoreChart()
    }

    // 分数段分布图
    const segmentChartEl = document.getElementById('segmentChart')
    if (segmentChartEl) {
      segmentChart = echarts.init(segmentChartEl)
      updateSegmentChart()
    }

    // 班级对比图
    const classChartEl = document.getElementById('classChart')
    if (classChartEl) {
      classChart = echarts.init(classChartEl)
      updateClassChart()
    }

    // 题目得分率图
    const questionChartEl = document.getElementById('questionChart')
    if (questionChartEl) {
      questionChart = echarts.init(questionChartEl)
      updateQuestionChart()
    }
  })
}

// 更新成绩分布图
const updateScoreChart = () => {
  if (!scoreChart || !gradeSheet.value) return

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['0-59', '60-69', '70-79', '80-89', '90-100']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      type: 'bar',
      data: [
        gradeSheet.value.failed_60 || 0,
        gradeSheet.value.score_60_69 || 0,
        gradeSheet.value.score_70_79 || 0,
        gradeSheet.value.score_80_89 || 0,
        gradeSheet.value.score_90_100 || 0
      ]
    }]
  }

  scoreChart.setOption(option)
}

// 更新分数段分布图
const updateSegmentChart = () => {
  if (!segmentChart || !gradeSheet.value) return

  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [{
      type: 'pie',
      radius: '60%',
      data: [
        { value: gradeSheet.value.score_a || 0, name: 'A (90-100)' },
        { value: gradeSheet.value.score_b || 0, name: 'B (80-89)' },
        { value: gradeSheet.value.score_c || 0, name: 'C (70-79)' },
        { value: gradeSheet.value.score_d || 0, name: 'D (60-69)' },
        { value: gradeSheet.value.score_f || 0, name: 'F (0-59)' }
      ]
    }]
  }

  segmentChart.setOption(option)
}

// 更新班级对比图
const updateClassChart = () => {
  if (!classChart || !gradeSheet.value) return

  // 模拟班级对比数据
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['一班', '二班', '三班', '四班']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      type: 'bar',
      data: [85, 78, 92, 88]
    }]
  }

  classChart.setOption(option)
}

// 更新题目得分率图
const updateQuestionChart = () => {
  if (!questionChart || !gradeSheet.value) return

  // 模拟题目数据
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['单选题', '多选题', '判断题', '填空题', '简答题']
    },
    yAxis: {
      type: 'value',
      max: 100
    },
    series: [{
      type: 'bar',
      data: [92, 85, 88, 75, 80],
      label: {
        show: true,
        position: 'top',
        formatter: '{c}%'
      }
    }]
  }

  questionChart.setOption(option)
}

// 重置筛选
const resetGradeFilter = () => {
  Object.assign(gradeFilter, {
    keyword: '',
    status: ''
  })
  gradesPage.value = 1
  loadGrades()
}

// 处理排序变化
const handleGradeSortChange = ({ prop, order }: any) => {
  gradeSortField.value = prop || ''
  gradeSortOrder.value = order || ''
  loadGrades()
}

// 查看学生试卷
const viewStudentPaper = (grade: any) => {
  // TODO: 实现查看学生试卷功能
  ElMessage.info('查看试卷功能开发中...')
}

// 查看学生详情
const viewStudentDetail = (grade: any) => {
  // TODO: 实现查看学生详情功能
  ElMessage.info('查看详情功能开发中...')
}

// 调整成绩
const adjustGrade = (grade: any) => {
  Object.assign(adjustForm, {
    grade_id: grade.id,
    student_name: grade.student_name,
    original_score: grade.score,
    new_score: grade.score,
    adjustment_type: 'manual',
    reason: ''
  })
  showAdjustDialog.value = true
}

// 确认调整
const confirmAdjust = async () => {
  try {
    // TODO: 实现成绩调整API调用
    ElMessage.success('成绩调整成功')
    showAdjustDialog.value = false
    loadGrades()
  } catch (error) {
    console.error('Failed to adjust grade:', error)
    ElMessage.error('调整失败')
  }
}

// 查看申诉详情
const viewAppealDetail = (appeal: any) => {
  // TODO: 实现查看申诉详情功能
  ElMessage.info('查看申诉详情功能开发中...')
}

// 通过申诉
const approveAppeal = async (appeal: any) => {
  try {
    // TODO: 实现申诉通过API调用
    ElMessage.success('申诉已通过')
    loadAppeals()
  } catch (error) {
    console.error('Failed to approve appeal:', error)
    ElMessage.error('处理失败')
  }
}

// 拒绝申诉
const rejectAppeal = async (appeal: any) => {
  try {
    // TODO: 实现申诉拒绝API调用
    ElMessage.success('申诉已拒绝')
    loadAppeals()
  } catch (error) {
    console.error('Failed to reject appeal:', error)
    ElMessage.error('处理失败')
  }
}

// 批量处理申诉
const handleAppeals = () => {
  ElMessage.info('批量处理申诉功能开发中...')
}

// 确认审核
const confirmReview = async () => {
  try {
    // TODO: 实现审核API调用
    await gradingApi.updateGradeSheet(sheetId, {
      status: reviewForm.status === 'approved' ? 'reviewed' : 'draft',
      review_notes: reviewForm.review_notes
    })
    ElMessage.success('审核成功')
    showReviewDialog.value = false
    loadGradeSheet()
  } catch (error) {
    console.error('Failed to review sheet:', error)
    ElMessage.error('审核失败')
  }
}

// 发布成绩单
const publishSheet = async () => {
  try {
    await gradingApi.publishGradeSheet(sheetId)
    ElMessage.success('发布成功')
    loadGradeSheet()
  } catch (error) {
    console.error('Failed to publish sheet:', error)
    ElMessage.error('发布失败')
  }
}

// 重新计算成绩
const calculateGrades = async () => {
  try {
    await gradingApi.calculateGrades(sheetId)
    ElMessage.success('重新计算成功')
    loadGradeSheet()
    loadGrades()
  } catch (error) {
    console.error('Failed to calculate grades:', error)
    ElMessage.error('计算失败')
  }
}

// 导出成绩
const exportGrades = async () => {
  try {
    // TODO: 实现导出功能
    ElMessage.info('导出功能开发中...')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 处理成绩单操作
const handleSheetAction = async (command: string) => {
  switch (command) {
    case 'export':
      exportGrades()
      break
    case 'report':
      generateReport()
      break
    case 'notify':
      sendNotification()
      break
    case 'delete':
      await deleteSheetConfirm()
      break
  }
}

// 生成报告
const generateReport = async () => {
  try {
    // TODO: 实现报告生成功能
    ElMessage.info('报告生成功能开发中...')
  } catch (error) {
    ElMessage.error('报告生成失败')
  }
}

// 发送通知
const sendNotification = async () => {
  try {
    // TODO: 实现发送通知功能
    ElMessage.info('发送通知功能开发中...')
  } catch (error) {
    ElMessage.error('发送通知失败')
  }
}

// 删除成绩单确认
const deleteSheetConfirm = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除成绩单 "${gradeSheet.value?.name}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await gradingApi.deleteGradeSheet(sheetId)
    ElMessage.success('删除成功')
    router.push('/grading/sheets')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete sheet:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理文件变化
const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

// 确认导入
const confirmImport = async () => {
  if (!importFile.value) return

  importLoading.value = true
  try {
    // TODO: 实现导入功能
    await new Promise(resolve => setTimeout(resolve, 2000)) // 模拟导入
    ElMessage.success('导入成功')
    showImportDialog.value = false
    loadGrades()
  } catch (error) {
    console.error('Import failed:', error)
    ElMessage.error('导入失败')
  } finally {
    importLoading.value = false
  }
}

// 返回
const goBack = () => {
  router.push('/grading/sheets')
}

// 编辑成绩单
const editSheet = () => {
  router.push(`/grading/sheets/${sheetId}/edit`)
}

// 工具函数
const formatDateTime = (dateString?: string) => {
  return dateString ? new Date(dateString).toLocaleString() : ''
}

const formatDate = (dateString?: string) => {
  return dateString ? new Date(dateString).toLocaleDateString() : ''
}

const formatDuration = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

const getStatusType = (status?: string) => {
  const types: Record<string, string> = {
    draft: 'info',
    reviewed: 'warning',
    published: 'success'
  }
  return types[status || ''] || 'info'
}

const getStatusText = (status?: string) => {
  const texts: Record<string, string> = {
    draft: '草稿',
    reviewed: '已审核',
    published: '已发布'
  }
  return texts[status || ''] || status
}

const getScoreClass = (score: number, passingScore?: number) => {
  return score >= (passingScore || 60) ? 'score-passed' : 'score-failed'
}

const getGradeType = (grade: string) => {
  const types: Record<string, string> = {
    'A': 'success',
    'B': 'success',
    'C': 'warning',
    'D': 'warning',
    'F': 'danger'
  }
  return types[grade] || 'info'
}

const getStudentStatusType = (status: string) => {
  const types: Record<string, string> = {
    submitted: 'success',
    passed: 'success',
    failed: 'danger',
    absent: 'info'
  }
  return types[status] || 'info'
}

const getStudentStatusText = (status: string) => {
  const texts: Record<string, string> = {
    submitted: '已提交',
    passed: '及格',
    failed: '不及格',
    absent: '缺考'
  }
  return texts[status] || status
}

const getAppealStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

const getAppealStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: '待处理',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

// 页面挂载时
onMounted(async () => {
  await loadGradeSheet()
  await Promise.all([
    loadGrades(),
    loadAppeals()
  ])
  initCharts()
})
</script>

<style scoped lang="scss">
.sheet-detail {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 24px;

    .back-btn {
      margin-bottom: 12px;
    }

    h1 {
      font-size: 28px;
      color: var(--el-text-color-primary);
      margin: 0 0 8px 0;
    }

    .sheet-meta {
      display: flex;
      align-items: center;
      gap: 16px;
      font-size: 14px;
      color: var(--el-text-color-regular);

      .creator {
        color: var(--el-text-color-placeholder);
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
      margin-top: 16px;
    }
  }

  .stats-row {
    margin-bottom: 24px;
  }

  .basic-info {
    .detail-info {
      margin-top: 24px;
      margin-bottom: 24px;
    }

    .chart-section {
      h3 {
        font-size: 16px;
        color: var(--el-text-color-primary);
        margin: 0 0 16px 0;
      }
    }
  }

  .grades-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .header-left {
        display: flex;
        gap: 12px;
        align-items: center;
      }

      .header-right {
        display: flex;
        gap: 8px;
      }
    }

    .score-value {
      font-weight: 500;
      &.score-passed {
        color: var(--el-color-success);
      }
      &.score-failed {
        color: var(--el-color-danger);
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 16px;
    }
  }

  .analysis-section {
    .analysis-card {
      margin-bottom: 20px;
      h3 {
        font-size: 16px;
        color: var(--el-text-color-primary);
        margin: 0 0 16px 0;
      }
    }
  }

  .appeals-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .header-left {
        display: flex;
        gap: 12px;
        align-items: center;

        h3 {
          font-size: 16px;
          margin: 0;
        }
      }
    }

    .appeal-reason {
      max-width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;
  }

  .import-content {
    .upload-area {
      margin-bottom: 20px;
    }

    .import-tips {
      h4 {
        font-size: 14px;
        margin: 0 0 12px 0;
      }

      ul {
        margin: 0;
        padding-left: 20px;

        li {
          font-size: 12px;
          color: var(--el-text-color-regular);
          margin-bottom: 4px;
        }
      }
    }
  }

  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-regular);
    margin-top: 4px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .sheet-detail {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;

      .header-right {
        flex-direction: column;
      }
    }

    .grades-section,
    .appeals-section {
      .section-header {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;

        .header-left {
          flex-wrap: wrap;
        }

        .header-right {
          justify-content: flex-start;
        }
      }

      .action-buttons {
        flex-direction: column;
        align-items: stretch;
      }
    }
  }
}
</style>